#include <iostream>
#include "CThread.h"

using namespace std;


class Test1 : public CThread
{
private:
    int sleep_time;

    void run()
    {
	sleep_time = 10;

        string name = getName();
	for(int i=0;i<6;i++) 
        {
	    if(sleep_time<0) break;

            try
            {
                cout << name << endl;
                sleep(sleep_time);
            }
            catch (InterruptedException& e)
            {
                cout << name << ": " << e.what();
                cout << " but continue" << endl;
            }
	    catch(IllegalThreadStateException& ie)
	    {
		cout << name << ": " << ie.what();
		cout << " but continue" << endl;
	    }
        }
        cout << name << " ending" << endl;
    }

public: 
    void setSleepTime(int sleeptime)
    {
	sleep_time = sleeptime;
    }

    int getSleepTime()
    {
	return sleep_time;
    }
};


class Test2 : public CThread
{
private:
    void run()
    {
        string name = getName();
	while(1)
        {
            cout << name << endl;
            sleep(1);
        }
        cout << name << " ending" << endl;
    }
};

class Test3 : public CThread
{
private:
    CThread& _t;
    
    void run()
    {
        cout << getName() << " is joinning " << _t.getName() << endl;
        _t.join();
        cout << getName() << " is ending" << endl;
    }
    
public:
    Test3(CThread& t) : _t(t) {}
};

void checkAlive(CThread& thread)
{
    string name = thread.getName();
    if (thread.isAlive())
    {
        cout << name << " is alive" << endl;
    }
    else
    {
        cout << name << " is died" << endl;
    }
}


void checkInterrupt(CThread& thread)
{
    string name = thread.getName();
    if (thread.isInterrupted())
    {
        cout << name << " is interrupted" << endl;
    }
    else
    {
        cout << name << " is not interrupted" << endl;
    }
}

int main()
{
        Test1 t1;
        Test2 t2;
	t1.setName("First Thread");
        t2.setName("Second Thread");
        t1.start();
        t2.start();
	//t2.interrupt();
	//t1.interrupt();
	//t1.setSleepTime(-1);
	t1.join();
	t2.interrupt();

	cout << "all finished" << endl;


/*
	string url = "localhost";
	string port = "8088";

	cout << endl << endl;
	while(1) {
		CKeepAliveThread keepalive(url, port);
		keepalive.keepAlive(5);
		keepalive.start();
		keepalive.join();
		cout << "okay again" << endl;
	}
	cout << "all of the things finished" << endl;
*/
}

